from fastapi import APIRouter, HTTPException, Depends, Query
from fastapi.responses import StreamingResponse
from typing import Optional

from database.database import Conversation, Message, User
from database.database_function import get_db
from api.utils import stream_response, mark_cancel
from api.schemas.chat import QuestionRequest, ConversationResponse, ConversationMessagesResponse, MessageResponse
from api.auth import get_current_active_user, require_permission


router = APIRouter()


@router.post("/stream-question", summary="获取流式问答结果")
async def get_stream_question(
    request: QuestionRequest, 
    current_user: User = Depends(require_permission("chat")),
    db=Depends(get_db)
):
    if not request.question.strip():
        raise HTTPException(status_code=400, detail="问题不能为空")

    conversation_id = request.conversation_id
    if conversation_id == 0:
        conversation_id = None

    return StreamingResponse(
        stream_response(
            request.question,
            conversation_id,
            db,
            request.model_name,
            getattr(request, 'system_prompt_id', None),
            getattr(request, 'kb_id', None),
            getattr(request, 'top_k', 6),
            getattr(request, 'threshold', 0.0),
            getattr(request, 'include_citations', True),
            current_user.user_id  # 传递用户ID
        ),
        media_type="text/event-stream; charset=utf-8",
        headers={
            "Cache-Control": "no-cache, no-transform",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no"
        }
    )


@router.get("/conversations/{conversation_id}", response_model=ConversationResponse, summary="获取指定会话信息（概要信息，不包含信息内容）")
async def get_conversation(
    conversation_id: int, 
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    conversation = db.query(Conversation).filter(
        Conversation.conversation_id == conversation_id,
        Conversation.user_id == current_user.user_id
    ).first()
    if not conversation:
        raise HTTPException(status_code=404, detail="会话不存在")
    return ConversationResponse(
        conversation_id=conversation.conversation_id,
        title=conversation.title,
        start_time=conversation.start_time,
        last_update_time=conversation.last_update_time,
        model_name=conversation.model_name or "",
        system_prompt_id=getattr(conversation, 'system_prompt_id', None),
        kb_id=getattr(conversation, 'kb_id', None)
    )


@router.get("/conversations/{conversation_id}/messages", response_model=ConversationMessagesResponse, summary="获取指定所有会话信息")
async def get_conversation_messages(
    conversation_id: int, 
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    conversation = db.query(Conversation).filter(
        Conversation.conversation_id == conversation_id,
        Conversation.user_id == current_user.user_id
    ).first()
    if not conversation:
        raise HTTPException(status_code=404, detail="会话不存在")
    messages = db.query(Message).filter(Message.conversation_id == conversation_id).order_by(Message.sequence).all()
    return ConversationMessagesResponse(
        conversation_id=conversation_id,
        messages=[
            MessageResponse(
                message_id=msg.message_id,
                sender_type=msg.sender_type,
                content=msg.content,
                send_time=msg.send_time,
                sequence=msg.sequence,
                citations=getattr(msg, 'citations', None)
            )
            for msg in messages
        ]
    )


@router.get("/conversations", summary="获取会话列表")
async def list_conversations(
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    conversations = db.query(Conversation).filter(
        Conversation.user_id == current_user.user_id
    ).order_by(Conversation.last_update_time.desc()).all()
    return {
        "conversations": [
            {
                "conversation_id": conv.conversation_id,
                "title": conv.title,
                "start_time": conv.start_time,
                "last_update_time": conv.last_update_time,
                "model_name": conv.model_name,
                "system_prompt_id": getattr(conv, 'system_prompt_id', None),
                "kb_id": getattr(conv, 'kb_id', None)
            }
            for conv in conversations
        ]
    }


@router.delete("/conversations/{conversation_id}", summary="删除指定会话及其消息")
async def delete_conversation(
    conversation_id: int, 
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    conversation = db.query(Conversation).filter(
        Conversation.conversation_id == conversation_id,
        Conversation.user_id == current_user.user_id
    ).first()
    if not conversation:
        raise HTTPException(status_code=404, detail="会话不存在")
    db.delete(conversation)
    db.commit()
    return {"success": True}


@router.post("/conversations/{conversation_id}/title", summary="用于修改聊天记录的标题")
async def modify_conversation_title(
    conversation_id: int, 
    title: str, 
    current_user: User = Depends(get_current_active_user),
    db=Depends(get_db)
):
    conversation = db.query(Conversation).filter(
        Conversation.conversation_id == conversation_id,
        Conversation.user_id == current_user.user_id
    ).first()
    if not conversation:
        raise HTTPException(status_code=404, detail="会话不存在")
    conversation.title = title
    db.commit()
    return {"success": True}


@router.post("/conversations/{conversation_id}/cancel", summary="取消指定会话的生成任务")
async def cancel_generation(
    conversation_id: int,
    current_user: User = Depends(get_current_active_user)
):
    try:
        mark_cancel(conversation_id)
        return {"success": True}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


